package github.kawaiior.botapiserver.util;

import cn.hutool.captcha.*;
import cn.hutool.core.util.RandomUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import static cn.hutool.captcha.CaptchaUtil.*;

public class CaptchaUtil {

    private static final int width = 300;
    private static final int height = 100;

    public static AbstractCaptcha getCaptcha(){
        int t = RandomUtil.randomInt(0, 3);
        if (t==0){
            return getLineCaptcha();
        }else if (t==1){
            return getCircleCaptcha();
        }else if (t==2){
            return getShearCaptcha();
        }
        return getLineCaptcha();
    }

    public static AbstractCaptcha getLineCaptcha(){
        return createLineCaptcha(width, height);
    }

    public static AbstractCaptcha getCircleCaptcha(){
        return createCircleCaptcha(width, height);
    }

    public static AbstractCaptcha getShearCaptcha(){
        return createShearCaptcha(width, height);
    }

    /**
     * 返回验证码图片
     * @return base64
     */
    public static String getCodeImg(HttpSession session) {
        AbstractCaptcha captcha = getCaptcha();
        String code = captcha.getCode();
        session.setAttribute("code", code);
        return captcha.getImageBase64Data();
    }

    public static boolean codeError(String userInputCode, HttpSession session){
        Object o = session.getAttribute("code");
        session.setAttribute("code", null);
        if (!(o instanceof String trueCode)){
            return true;
        }
        return !trueCode.equalsIgnoreCase(userInputCode);
    }

}
